import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import Login from '@/views/app/Login.vue';
import common from '@/lib/common';
import routerList from './routerList';
import noLoginRoute from "./noLoginRoute";
import storage from '@/lib/storage/storage';
import utils from '@/lib/utils';
import message from '@/lib/message';

// 框架主题页面数组
const HomeArr: any = [
  // 经典
  () => import("@/views/app/home/homeClassic/HomeClassic.vue"),
  // 现代 仿win10
  () => import("@/views/app/home/homeWin/HomeWin.vue")
];

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Login',
    component: Login,
    meta: {
      title: "登录",
    }
  },
  {
    path: '/home',
    name: 'Home',
    component: HomeArr[common.homeTheme()],
    meta: {
      title: "主页",
    },
    children: routerList
  },
  {
    path: '/**',
    redirect: '/',
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});


/*
* 访问路由之前
 */
router.beforeEach((to, from, next) => {
  const index = noLoginRoute.findIndex((path) => path === to.path);
  if (index >= 0) {
    next();
  } else {
    const token = storage.token.Get();
    if (utils.empty(token)) {
      message.alert("您没有登陆或登陆已经过期，请重新登陆").then(() => {
        next({ path: window.CONFIG.loginPage });
      });
    } else {
      const menuList = storage.menuList.Get();
      const menuIndex = menuList.findIndex((item: any) => item.route === to.path);
      if (menuIndex < 0) {
        next({ path: from.path });
      } else {
        next();
      }
    }
  }
});

/*
const originalPush: any = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location: any) {
  return originalPush.call(this, location).catch((err: any) => err);
};
*/
export default router;
